package br.com.ufrj.ppgi.helloandre;

import java.io.File;
import java.util.HashMap;

import jxl.Cell;
import jxl.CellType;
import jxl.Sheet;
import jxl.Workbook;
import android.util.Log;

import com.thetransactioncompany.jsonrpc2.JSONRPC2Request;

public class LeXls implements Runnable{
	
	private static final String INTERVALO = "#interval";
	private String inputFile;
	private int row;
	
	@Override
	public void run() {
		setInputFile("sdcard/simulador.xls");
		row = -1;
	}

	public String createMessage(int request) {
		// The remote method to call
		String method;// = "addPOI";
		// The mandatory request ID
		String id = "req"+request;
		File inputWorkbook = new File(inputFile);
		String ret = null;
		Workbook w;
		try {
			row++;
			w = Workbook.getWorkbook(inputWorkbook);
			Sheet sheet = w.getSheet(0);
			HashMap<String, String> params = new HashMap<String, String>();
			int col = sheet.getColumns();
			Cell cell = sheet.getCell(0, row), cell1 = sheet.getCell(1, row);
			if (cell.getType() == CellType.EMPTY) {
				ret = null;
			}
			else {
				if (cell.getContents().equals(INTERVALO)) {
					try {
						Thread.sleep(Integer.valueOf(cell1.getContents()) * 1000);
						Log.v(INTERVALO, INTERVALO);
						row++;
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				method = sheet.getCell(1, row).getContents();
				for (int j = 2; j + 1 < col; j+=2) {
					cell = sheet.getCell(j, row);
					cell1 = sheet.getCell(j+1, row);
					if (cell.getType() == CellType.EMPTY) {
						if (sheet.getCell(j + 1, row).getType() == CellType.EMPTY) {
							break;
						}
					}
					params.put(cell.getContents(), cell1.getContents());
				}
				// Create a new JSON-RPC 2.0 request
				JSONRPC2Request reqOut= new JSONRPC2Request(method, params, id);
				ret = reqOut.toString();
			}
			} catch (Exception e) {
				e.printStackTrace();
			}
		
		return ret;

	}

	private void setInputFile(String inputFile) {
		this.inputFile = inputFile;
	}
		
}
